package com.dlwx.firefighting.activity;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dlwx.firefighting.R;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.utils.CheckUtil;
import com.dlwx.firefighting.utils.DealResult;
import com.dlwx.firefighting.utils.KeyBoardUtils;
import com.dlwx.firefighting.utils.MD5Util;
import com.dlwx.firefighting.utils.TimeCount;
import com.dlwx.firefighting.utils.ToastUtils;
import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppInstallListener;
import com.fm.openinstall.model.AppData;
import com.fm.openinstall.model.Error;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 注册界面
 */
public class RegisterActivity extends BaseActivity {

    @BindView(R.id.register_back)
    ImageView img_back;
    @BindView(R.id.register_edit_phone)
    EditText edit_phone;
    @BindView(R.id.register_edit_psw)
    EditText edit_psw;
    @BindView(R.id.register_edit_yzm)
    EditText edit_yzm;
    @BindView(R.id.register_yzm)
    TextView btn_yzm;
    @BindView(R.id.button_register)
    TextView btn_register;
    private String phoneNum;
    private String yzm;
    private String psw;

    private TimeCount timeCount = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);

        //倒计时
        timeCount = new TimeCount(btn_yzm, 120*1000, 1000);
        //设置状态栏
       // MyStatusBar.setStatusBar(RegisterActivity.this, ContextCompat.getColor(this, R.color.white), 0);
        //编辑框触摸显示光标
        edit_phone.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    edit_phone.setCursorVisible(true);
                }
                return false;
            }
        });
        edit_phone.addTextChangedListener(textWatcher);
        edit_psw.addTextChangedListener(textWatcher);
        edit_yzm.addTextChangedListener(textWatcher);
        getInviteCode();
    }

    private void getInviteCode() {
        OpenInstall.getInstall(new AppInstallListener() {
            @Override
            public void onInstallFinish(AppData appData, Error error) {
                if (error == null) {
                    if (appData == null) return;
                    //获取自定义数据
                    Log.d("OpenInstall", "getInstall : bindData = " + appData.getData());
                    //获取渠道数据
                    Log.d("OpenInstall", "getInstall : channelCode = " + appData.getChannel());
                } else {
                    Log.e("OpenInstall", "getInstall : errorMsg = " + error.toString());
                }
            }
        });
    }

    @OnClick({R.id.register_back, R.id.register_yzm, R.id.button_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.register_back:
                finish();
                break;
            case R.id.register_yzm:
                phoneNum= edit_phone.getText().toString();
                if (CheckUtil.isPhoneNum(phoneNum) && phoneNum.length() == 11) {
                    getYzm();
                }else {
                    edit_phone.setText("");
                    ToastUtils.toastForLong(RegisterActivity.this, "手机号码格式错误");
                }
                break;
            case R.id.button_register:
                if (checkUserInfo()) {
                    KeyBoardUtils.closeKeybord(RegisterActivity.this);
                    register();
//                    ToastUtils.toastForLong(RegisterActivity.this, "注册");
                }
                break;
        }
    }


    private void getYzm() {
        OkGo.<String>post(Constant.YZM)
                .tag(this)
                .params("phoneNumber",phoneNum)
                  /*   1、注册 2、找回密码*/
                .params("type",1)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        int code =  DealResult.getInstance().deal(RegisterActivity.this, response);
                        if(code==Constant.SUCESS){
                            timeCount.start();
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForLong(RegisterActivity.this,  getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }
    private void register() {
        psw=MD5Util.getMD5(psw);
        OkGo.<String>post(Constant.REGISTER)
                .tag(this)
                .params("phoneNumber",phoneNum)
                  /*   1、注册 2、找回密码*/
                .params("userPwd",psw)
                .params("vcode",yzm)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        int code =  DealResult.getInstance().deal(RegisterActivity.this, response);
                        if(code==Constant.SUCESS){
                           RegisterActivity.this.finish();
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForLong(RegisterActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }


    /**
     * 检查用户名和密码格式
     */
    private boolean checkUserInfo() {
        phoneNum = edit_phone.getText().toString();
        psw = edit_psw.getText().toString();
        yzm= edit_yzm.getText().toString();
        if (!CheckUtil.isPhoneNum(phoneNum)) {
            edit_phone.setText("");
            ToastUtils.toastForLong(RegisterActivity.this, "手机号码格式错误");
            return false;
        }
        if (!CheckUtil.checkPassword(psw) || psw.length() < 6) {
            edit_psw.setText("");
            ToastUtils.toastForLong(RegisterActivity.this, "密码格式错误");
            return false;
        }
        if (yzm.length() < 6) {
            edit_yzm.setText("");
            ToastUtils.toastForLong(RegisterActivity.this, "验证码错误");
            return false;
        }
        return true;
    }

    /**
     * 当手机号码长度为11，密码长度大于5,验证码长度为6时，登陆按钮变亮，否则变暗
     */
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String phone = edit_phone.getText().toString();
            String password = edit_psw.getText().toString();
            String yanzhengma = edit_yzm.getText().toString();
//            if (phone.length() == 11 && password.length() > 5 && yanzhengma.length() == 6) {
//                btn_register.setBackgroundResource(R.drawable.bg_green_selector);
//            } else {
//                btn_register.setBackgroundResource(R.drawable.bg_grey);
//            }

//            if (phone.length() == 11) {
//                btn_yzm.setBackgroundResource(R.drawable.bg_green);
//            } else {
//                btn_yzm.setBackgroundResource(R.drawable.bg_grey);
//            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeCount != null) {
            timeCount.cancel();
            timeCount=null;
        }
    }

    //-----------------------------------------------------------
}
